package com.yxx.controller.user;

import com.yxx.medicinecommon.constant.JwtClaimsConstant;
import com.yxx.medicinecommon.context.BaseContext;
import com.yxx.medicinecommon.properties.JwtProperties;
import com.yxx.medicinecommon.result.ResponseResult;
import com.yxx.medicinecommon.utils.JwtUtil;
import com.yxx.medicinepojo.dto.UserLoginDTO;
import com.yxx.medicinepojo.entity.User;
import com.yxx.medicinepojo.vo.UserLoginVO;
import com.yxx.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.xml.transform.Result;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yuxiangxun
 * @date 2024/9/23
 * @apiNote
 */
@RestController
@Slf4j
@RequestMapping("/user/user")
@Api(tags = "微信用户相关接口")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("微信登录")
    public ResponseResult<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("微信用户登录：{}",userLoginDTO.getCode());

        //微信登录
        User user = userService.wxLogin(userLoginDTO);

        //为微信用户生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();
        return ResponseResult.success(userLoginVO);
    }

    @GetMapping("/phone")
    @ApiOperation("获取手机号")
    public ResponseResult<String>getPhone(){
        String phone = userService.getPhone(BaseContext.getCurrentId());
        if(StringUtils.isEmpty(phone)){
            phone="请输入号码";
        }
        return ResponseResult.success(phone);
    }
}
